/**
 * 将数字进行千分位格式化
 * @param num
 * @returns {string}
 */
export function toThousandFilter(num) {
  return (+num || 0)
    .toString()
    .replace(/^-?\d+/g, (m) => m.replace(/(?=(?!\b)(\d{3})+$)/g, ","));
}

/**
 * 对数字进行万位格式化
 * @param num
 * @param digits
 * @returns {string}
 */
export function numberFormatter2(num = 0, digits) {
  const si = [
    { value: 1e12, symbol: "万亿" },
    { value: 1e8, symbol: "亿" },
    { value: 1e4, symbol: "万" },
  ];
  for (let i = 0; i < si.length; i++) {
    if (num >= si[i].value) {
      return (
        (num / si[i].value)
          .toFixed(digits)
          .replace(/\.0+$|(\.[0-9]*[1-9])0+$/, "$1") + si[i].symbol
      );
    }
  }
  return num.toString();
}

/**
 * 对数字进行万位格式化
 * @param num
 * @param digits
 * @returns {string}
 */
export function toThousandAndFormat(num = 0, digits) {
  const si = [
    // { value: 1E12, symbol: '万亿' },
    // { value: 1E8, symbol: '亿' },
    { value: 1e4, symbol: "万" },
  ];
  let n = num;
  let unit = "";
  for (let i = 0; i < si.length; i++) {
    if (num >= si[i].value) {
      n = (num / si[i].value)
        .toFixed(digits)
        .replace(/\.0+$|(\.[0-9]*[1-9])0+$/, "$1");
      unit = si[i].symbol;
      break;
    }
  }
  return toThousandFilter(n) + unit;
}

export function toThousandAndFormat2(num = 0, digits) {
  const si = [
    { value: 1e12, symbol: "万亿" },
    { value: 1e4, symbol: "万" },
    { value: 1e4, symbol: "万" },
  ];
  let n = num;
  let unit = "";
  for (let i = 0; i < si.length; i++) {
    if (num >= si[i].value) {
      n = (num / si[i].value)
        .toFixed(digits)
        .replace(/\.0+$|(\.[0-9]*[1-9])0+$/, "$1");
      unit = si[i].symbol;
      break;
    }
  }
  return toThousandFilter(n) + unit;
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string") {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time);
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), "/");
      }
    }

    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    return value.toString().padStart(2, "0");
  });
  return time_str;
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (("" + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;
  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatStr(str) {
  return Number(str.substr(0, str.length - 1));
}

/**
 * 对象里某个属性进行升序
 * @param {strind} name
 * @returns {string}
 */
export function ascend(name) {
  return (a, b) => {
    return b[name] - a[name];
  };
}

/**
 * 判断是否在iframe里面, 如果是的话, 则定位要减去 64px 的高度
 * @param px top或者left的值
 * @param direction 方向, 默认是top, bottom是加上, top是减去
 */
const isInYZHIframe = window.top === window;
export function iframePositionDiff(px, direction = "top") {
  return direction === "bottom"
    ? `${isInYZHIframe ? px + 64 : px}px`
    : `${isInYZHIframe ? px - 64 : px}px`;
}

//#region 原大屏工程的tools

let screenWidth = document.body.clientWidth / 30.4;
if (screenWidth > 100) {
  screenWidth = 100;
}
window.addEventListener("resize", () => {
  screenWidth = document.body.clientWidth / 30.4;
  if (screenWidth > 100) {
    screenWidth = 100;
  }
});

export function ifIE() {
  const userAgent = navigator.userAgent; // 取得浏览器的userAgent字符串
  const isIE =
    userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; // 判断是否IE<11浏览器
  const isIE11 =
    userAgent.indexOf("Trident") > -1 && userAgent.indexOf("rv:11.0") > -1;
  return isIE || isIE11;
}

/**
 * 根据传入的 text，复制到粘贴板，返回复制结果
 * @param {String} text 复制的文本
 * @return {Boolean} 复制结果
 */
export function copyText(text) {
  text = typeof text === "string" ? text : "";
  const input = document.createElement("input");
  input.setAttribute("readonly", "readonly");
  input.setAttribute("value", text);
  document.body.appendChild(input);
  input.select();
  try {
    document.execCommand("copy");
    document.body.removeChild(input);
    return true;
  } catch (e) {
    document.body.removeChild(input);
    return false;
  }
}

// console.log(screenWidth);
export function rem2px(rem) {
  rem = rem.toString().replace("rem", "");
  return rem * screenWidth;
}

//#endregion
